<template>
  <div class="chat-container">
    <!-- 左侧：会话管理 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <el-button type="primary" @click="openCreateDialog"  icon="Plus">新建会话</el-button>
      </div>

      <div class="current-chat">
        <!-- 标题行：包含“当前会话”文本和“管理对话记录”按钮 -->
        <div class="current-chat-header">
            <h4>当前会话</h4>
            <el-button type="info"  @click="openManageDialog" class="manage-btn-inline">管理会话历史</el-button>
        </div>
        <el-select
          v-model="currentChatId"
          placeholder="选择会话"
          @change="onChatChange"
          style="width: 100%; margin-bottom: 16px;"
        >
          <el-option
            v-for="chat in chatList"
            :key="chat.id"
            :label="chat.name"
            :value="chat.id"
          />
        </el-select>

        <!-- 当前会话信息展示 -->
        <div v-if="currentChat" class="chat-info">
          <p><strong>角色卡：</strong>{{ currentChat.roleCard || '无' }}</p>
          <p><strong>备注：</strong>{{ currentChat.remark || '无' }}</p>
          <p><strong>开始时间：</strong>{{ formatDate(currentChat.startTime) }}</p>
          <p><strong>最后会话时间：</strong>{{ formatDate(currentChat.lastTime) }}</p>
        </div>
        <div v-else class="chat-info placeholder">会话详情</div>
      </div>
      <!-- 角色管理，跳转到角色管理页面 -->
      <div>
        <el-button type="primary" @click="goToRoleManagement">角色管理</el-button>
      </div>

    </div>

    <!-- 右侧：对话界面 -->
    <div class="main-content">
      <!-- 2D角色展示区域 -->
      <div class="character-display">
        <!-- 预留区域，可嵌入Live2D模型或其他组件 -->
        <Live2DDisplay
          ref="live2dRef"
          :model-path="live2dModelPath"
          :scale="0.5"
          :x-ratio="0.5"
          @model-loaded="handleLive2dLoaded"
          @load-failed="handleLive2dFailed"
        />
      </div>

      <!-- 聊天输入区域 -->
      <div class="chat-input-area">
        <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="5"
            :autosize="{ minRows: 5, maxRows: 6 }"
            placeholder="请输入消息..."
            @keyup.enter="handleEnterKey"
            maxlength="2000"  
            show-word-limit   
            class="message-textarea"
        />
        <!-- 发送和麦克风按钮在同一行 -->
        <div class="send-mic-controls">
            <el-button type="primary" @click="sendMessage" icon="Position" :disabled="!inputMessage.trim()">发送(shift+enter换行，enter发送)</el-button>
            <el-button
            :type="isListening ? 'danger' : 'default'"
            @click="toggleMic"
            icon="Microphone"
            >
            {{ isListening ? '关闭麦克风' : '开启麦克风' }}
            </el-button>
            <el-button type="info" icon="User" @click="openChatHistory">聊天记录</el-button>
        </div>
      </div>
    </div>

    <!-- 父组件中使用 -->
    <ChatHistoryDialog 
        :chat-id="currentChatId" 
        v-model:visible="showChatHistoryDialog" 
    />

    <!-- 新增：新建会话弹窗 -->
    <el-dialog
    v-model="showCreateDialog"
    title="新建会话"
    width="800px"
    :close-on-click-modal="false"
    @opened="onDialogOpened"
    >
    <el-form :model="newChatForm" label-width="80px" style="padding: 0 20px;">
    <el-form-item label="会话名称" required>
        <el-input
        ref="chatNameInputRef"
        v-model="newChatForm.name"
        placeholder="请输入会话名称"
        maxlength="30"
        show-word-limit
        @keyup.enter="createChat"
        />
    </el-form-item>

    <!-- 新增：角色卡选择 -->
<el-form-item label="角色卡" required>
  <div style="display: flex; align-items: center; gap: 4px;">
    <el-select
      v-model="newChatForm.roleCard"
      placeholder="请选择角色卡"
      style="flex: 1; min-width: 200px;"
    >
      <el-option
        v-for="item in roleCardOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-button
      icon="Refresh"
      type="primary"
      @click="refreshRoleCards"
    />
  </div>
</el-form-item>

    <el-form-item label="备注">
        <el-input
        v-model="newChatForm.remark"
        type="textarea"
        :rows="3"
        placeholder="请输入备注（可选）"
        maxlength="100"
        show-word-limit
        />
    </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="showCreateDialog = false" size="small">取消</el-button>
        <el-button type="primary" @click="createChat" size="small" :disabled="!newChatForm.name.trim()">
        确定
        </el-button>
    </template>
    </el-dialog>


    <!-- 管理会话历史的弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="管理会话历史"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-table :data="chatList" style="width: 100%" border>
        <el-table-column prop="name" label="会话名称" width="250">
          <template #default="{ row }">
            <el-input v-if="row.edit" v-model="row.tempName" size="small" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" width="300">
          <template #default="{ row }">
            <el-input
              v-if="row.edit"
              v-model="row.tempRemark"
              type="textarea"
              :rows="4" 
              resize="vertical"  
              maxlength="200"  
              show-word-limit  
              size="small"
            />
            <span v-else>{{ row.remark || '无' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="roleCard" label="角色卡" width="120">
          <template #default="{ row }">
            {{ row.roleCard || '无' }}
          </template>
        </el-table-column>

        <el-table-column prop="startTime" label="开始时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="lastTime" label="最后会话时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.lastTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <div v-if="row.edit">
              <el-button size="small" type="success" @click="saveEdit(row)">保存</el-button>
              <el-button size="small" @click="cancelEdit(row)">取消</el-button>
            </div>
            <div v-else>
              <el-button size="small" @click="startEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteChat(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed,nextTick,onMounted  } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ChatHistoryDialog from '@/components/chatHistoryDialog.vue'
import * as characterCardApi from '@/api/characterCard_api'  //请求后台角色卡列表
import * as chatSessionApi from '@/api/chatSession_api'  //请求后台会话列表
import * as chatApi from '@/api/chat_api'  //请求后台发送消息;

import Live2DDisplay from '@/components/Live2DDisplay.vue'

// 2. 新增Live2D相关状态
const live2dRef = ref(null) // Live2D子组件引用
const live2dModelPath = ref('/live2d/Haru/Haru.model3.json')

onMounted(() => {
  refreshRoleCards(false); // 初始加载时不显示提示
  fetchChatSessions(); // 初始加载会话列表
})

// 4. Live2D子组件回调处理（可选）
const handleLive2dLoaded = (model) => {
  console.log('Live2D模型加载完成', model)
  // 可在这里添加模型加载后的额外逻辑（如自动播放动画）
}

const handleLive2dFailed = (error) => {
  console.error('Live2D模型加载失败', error)
  // 可在这里添加错误恢复逻辑（如切换备用模型）
}

// 5. 如需控制表情，调用子组件暴露的方法
// 示例：在发送消息后切换表情
const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }
  // ... 原有发送逻辑 ...
  try{
    const response = await chatApi.sendText({
      session_id: currentChatId.value,
      message: inputMessage.value.trim()
    })
    if (response.data.code == 0){
      ElMessage.success('消息发送成功')
      //解析文本和音频文件
      

      inputMessage.value = ''
    }else{
      ElMessage.error('消息发送失败: ' + response.data.message)
    }
  }catch(error){
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }

  // 调用子组件的表情切换方法（示例：切换"happy"表情）
  //live2dRef.value?.changeExpression('happy')
}

// 6. 如需动态切换模型（示例）
const switchLive2dModel = (newPath) => {
  live2dModelPath.value = newPath // 子组件会自动监听路径变化并重新加载
}


// 模拟聊天会话数据
const chatList = ref([
  {
    id: 1,
    name: '与小助手的对话',
    remark: '测试会话',
    roleCard: '助手',
    startTime: new Date(2025, 8, 28, 10, 30),
    lastTime: new Date(),
    edit: false,
    tempName: '',
    tempRemark: ''
  },
  {
    id: 2,
    name: '学习规划讨论',
    remark: '关于AI学习路径',
    roleCard: '导师',
    startTime: new Date(2025, 8, 27, 15, 0),
    lastTime: new Date(2025, 8, 27, 16, 20),
    edit: false,
    tempName: '',
    tempRemark: ''
  }
])

// 预设角色卡列表
const roleCardOptions = ref(null)

//刷新角色卡列表
const refreshRoleCards = async (refresh = true) => {
  try {
    const params = { enabled: 1 } // 只获取启用的角色卡
    const res = await characterCardApi.getCharacterCards(params)
    if (res.data.code === 0) {
      const cards = res.data.data
      roleCardOptions.value = cards.map(card => ({
        value: card.id,
        label: card.name
      }))
      if (refresh)ElMessage.success('角色卡列表已刷新')
    } else {
      ElMessage.error('获取角色卡失败: ' + res.data.message)
    }
  } catch (error) {
    console.error('获取角色卡列表失败:', error)
    ElMessage.error('获取角色卡列表失败')
  }
}


// 更新表单对象，加入 roleCard
const newChatForm = ref({
  name: '',
  remark: '',
  roleCard: '' // 默认值
})

const showChatHistoryDialog = ref(false) // 控制弹窗显示的开关

// 新增：新建会话弹窗控制
const showCreateDialog = ref(false)

// 新增：用于自动聚焦输入框
const chatNameInputRef = ref()


// 新增：打开新建会话弹窗
const openCreateDialog = () => {
    //初始化newChatForm
    newChatForm.value = { name: '', remark: '', roleCard: '' }
    showCreateDialog.value = true
    // 使用 nextTick 确保 DOM 渲染完成后再聚焦
    // nextTick(() => {
    //     chatNameInputRef.value?.focus()
    // })
}

// 新增：当弹窗打开后自动聚焦（备用）
const onDialogOpened = () => {
  chatNameInputRef.value?.focus()
}

// 当前选中的会话ID
const currentChatId = ref('')

// 计算当前会话对象
const currentChat = computed(() => {
  return chatList.value.find(c => c.id === currentChatId.value)
})

// 输入消息与麦克风状态
const inputMessage = ref('')
const isListening = ref(false)

// 弹窗控制
const dialogVisible = ref(false)

// 格式化日期显示
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// ✅ 新增：处理回车键，避免直接换行，按下 Ctrl+Enter 换行
const handleEnterKey = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault() // 阻止默认换行行为
    sendMessage()          // 触发发送
  }
  // 如果需要换行，可以按 Shift+Enter 或 Ctrl+Enter
}

// 新建会话
const createChat = async () => {
  const name = newChatForm.value.name.trim()
  const roleCard = newChatForm.value.roleCard
  console.log("name: "+name)
  console.log("roleCard: "+roleCard)

  if (!name) {
    ElMessage.warning('请输入会话名称')
    return
  }
  if (!roleCard) {
    ElMessage.warning('请输入或选择角色卡')
    return
  }

  const newChat = {
    session_name: name,
    remark: newChatForm.value.remark.trim(),
    character_id: roleCard // 使用用户选择/输入的角色卡
  }
  let sessionId = null
  //请求后台创建会话
  try {
    const response = await chatSessionApi.createChatSession(newChat)
    if (response.data.code === 0) {
        sessionId = response.data.data.id // 假设返回的会话ID在 data.id
    } else {
        ElMessage.error('创建会话失败: ' + response.data.message)
        return
    }
  } catch (error) {
    console.error('创建会话失败:', error)
    ElMessage.error('创建会话失败')
    return
  }

  //重新请求后台会话列表
  fetchChatSessions();

  currentChatId.value = sessionId // 切换到新创建的会话

  showCreateDialog.value = false
  // 重置表单
  newChatForm.value = { name: '', remark: '', roleCard: '' }
  ElMessage.success('会话创建成功')
}

//请求后台会话列表
const fetchChatSessions = async () => {
  try {
    const response = await chatSessionApi.getChatSessions()
    if (response.data.code === 0) {
        chatList.value = response.data.data.map(session => ({
            id: session.id,
            name: session.session_name,
            remark: session.remark,
            character_id: session.character_id,
            roleCard: roleCardOptions.value?.find(card => card.value === session.character_id)?.label || '无',
            startTime: new Date(session.start_time),
            lastTime: new Date(session.last_active_time),
            edit: false,
            tempName: '',
            tempRemark: ''
        }))
    } else {
        ElMessage.error('获取会话列表失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    ElMessage.error('获取会话列表失败')
  }
}



// 切换当前会话
const onChatChange = (id) => {
  const chat = chatList.value.find(c => c.id === id)
  if (chat) {
    ElMessage.info(`切换到会话：${chat.name}`)
  }
}

// 打开管理对话框
const openManageDialog = () => {
  //请求会话列表，确保是最新的
  fetchChatSessions();
  // 初始化每个聊天项的临时字段
  chatList.value.forEach(chat => {
    if (!chat.hasOwnProperty('tempName')) {
      chat.tempName = chat.name
      chat.tempRemark = chat.remark || ''
    }
  })
  dialogVisible.value = true
}

//打开聊天记录弹窗
const openChatHistory = () => {
    if (!currentChatId.value) {
        ElMessage.warning('请先选择一个会话')
        return
    }
  console.log("currentChatId"+currentChatId.value)
  showChatHistoryDialog.value = true
}

// 开始编辑
const startEdit = (row) => {
  row.tempName = row.name
  row.tempRemark = row.remark || ''
  row.edit = true
}

// 保存编辑
const saveEdit = async (row) => {
  row.name = row.tempName.trim() || '未命名会话'
  row.remark = row.tempRemark
  try {
    //请求后台更新会话
    const data = {
        id: row.id,
        session_name: row.name,
        remark: row.remark
    }
    const response = await chatSessionApi.updateChatSession(row.id, data)
    if (response.data.code === 0) {
        // 更新成功
        ElMessage.success('会话更新成功')
    } else {
        ElMessage.error('更新会话失败: ' + response.data.message)
        return
    }
  } catch (error) {
    console.error('更新会话失败:', error)
    ElMessage.error('更新会话失败')
    return
  }
  //重新请求会话列表
  fetchChatSessions();

  row.edit = false
}

// 取消编辑
const cancelEdit = (row) => {
  row.edit = false
}

// 删除会话
const deleteChat = (row) => {
  ElMessageBox.confirm(`确定删除会话 "${row.name}" 吗？`, '警告', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消'
  }).then(async () => {
    //请求后台删除会话
    const response = await chatSessionApi.deleteChatSession(row.id)
    if (response.data.code === 0) {
        ElMessage.success('会话删除成功')
    } else {
        ElMessage.error('删除会话失败: ' + response.data.message)
        return
    }
    //重新请求会话列表
    fetchChatSessions();
    // 如果删除的是当前会话，清空选择
    if (currentChatId.value === row.id) {
      currentChatId.value = ''
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 切换麦克风
const toggleMic = () => {
  isListening.value = !isListening.value
  ElMessage.info(isListening.value ? '麦克风已开启' : '麦克风已关闭')
}

const goToRoleManagement = () => {
  // 假设角色管理页面路由为 /role-management
  window.open('/characterCard', '_blank')
}


</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  font-family: Arial, sans-serif;
}

/* 左侧边栏 */
.sidebar {
  width: 320px;
  background-color: #f5f7fa;
  padding: 20px;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}

.sidebar-header {
  margin-bottom: 20px;
}

.current-chat {
  margin-bottom: 20px;
}

.chat-info {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  background-color: #ffffff;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.chat-info.placeholder {
  text-align: center;
  color: #999;
}

.manage-btn {
  margin-top: 20px;
  text-align: center;
}

/* 右侧主内容 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  overflow: hidden; /* 防止子组件撑开整个主内容区 */
}

.character-display {
  flex: 1;
  min-height: 300px; /* 保证至少有300px高度，可根据需求调整 */
  max-height: calc(100vh - 200px); /* 最大高度 = 窗口高度 - 输入区/边距高度 */
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  background-color: #f9f9f9;
  color: #999;
  font-size: 16px;
  overflow: hidden; /* 隐藏超出容器的模型部分 */
}

/* 新增：优化文本域和按钮布局 */
.chat-input-area {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: stretch;
}

.message-textarea {
  flex: 1;
  --el-input-border-color: #dcdfe6;
  --el-input-hover-border-color: #c0c4cc;
}


.chat-input-area .el-input {
  flex: 1;
}

/* 发送和麦克风按钮区域 - 水平布局 */
.send-mic-controls {
  display: flex;
  gap: 10px;
}

.send-mic-controls .el-button {
  flex: 1; /* 平均分配宽度 */
}

/* 响应式优化 */
@media (max-width: 768px) {
  .send-mic-controls {
    flex-direction: column;
  }
  
  .send-mic-controls .el-button {
    max-width: none;
    width: 100%;
  }
}

/* 新增：当前会话标题行样式 */
.current-chat-header {
  display: flex;
  justify-content: space-between; /* 左右对齐 */
  align-items: center;           /* 垂直居中 */
  margin-bottom: 12px;           /* 与下一项保持间距 */
}

.current-chat-header h4 {
  margin: 0; /* 去除默认标题边距 */
}

.manage-btn-inline {
  /* 保持按钮大小一致 */
  margin-left: 8px; /* 与标题保持一点距离 */
}
</style>